package com.zrrd._11_network.udp.no_02;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * @author WanJl
 * @version 1.0
 * @title Receive
 * @description 接收端
 * @create 2023/10/28 21:34
 */
public class Receive {
    public void receive() {
        MulticastSocket ms = null;
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入组播地址：");
        String multicastHost = sc.nextLine();
        System.out.println("请输入端口号：");
        String portStr = sc.nextLine();
        int port = Integer.parseInt(portStr);
        System.out.println("组播地址及端口号配置完成，开始接受数据....");
        while (true) {
            try {
                //1、创建接收端Socket对象(MulticastSocket)
                ms=new MulticastSocket(port);
                //2、创建一个箱子,用于接收数据
                DatagramPacket dp=new DatagramPacket(new byte[1024],1024);
                //3、把当前计算机绑定一个组播地址
                ms.joinGroup(InetAddress.getByName(multicastHost));
                //4、将数据接收到箱子中
                ms.receive(dp);
                //5、解析数据包,并打印数据
                String s = new String(dp.getData(), 0, dp.getLength());
                System.out.println("接收到组播数据："+s);

                if (s.equals("886")) {
                    System.out.println("组播数据接收结束...");
                    break;
                }
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //5、关闭接收端
                ms.close();
            }
        }
    }
}
